import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:merchants/models/app_config.dart';
import 'package:merchants/models/session.dart';
import 'package:merchants/providers/providers.dart';
import 'package:merchants/providers/session_provider.dart';
import 'package:merchants/utils/we-chat-auth-result.dart';
import 'package:merchants/env.dart';
import 'package:merchants/utils/we-chat-manager.dart';
import 'package:merchants/utils/agreement_manager.dart';
import 'package:merchants/providers/agreement_provider.dart';

class LoginScreen extends ConsumerStatefulWidget {
  const LoginScreen({super.key});

  @override
  LoginScreenState createState() => LoginScreenState();
}

class LoginScreenState extends ConsumerState<LoginScreen> {
  bool _isWeChatInstalled = false;
  bool _isLoading = false;
  StreamSubscription<WeChatAuthResult>? _authSubscription;
  final Color _primaryColor = const Color(0xFF1A73E8);
  final Color _backgroundStart = const Color(0xFFF5F7FA);
  final Color _backgroundEnd = Colors.white;

  @override
  void initState() {
    super.initState();
    _checkWeChatInstalled();
    _listenToWeChatResponse();
  }

  Future<void> _checkWeChatInstalled() async {
    try {
      bool installed = await WeChatManager.isWeChatInstalled();
      if (mounted) {
        setState(() {
          _isWeChatInstalled = installed;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isWeChatInstalled = false;
        });
      }
    }
  }

  void _listenToWeChatResponse() {
    _authSubscription = WeChatManager.authResponseStream.listen((result) async {
      if (result.success) {
        if (!mounted) {
          return;
        }
        if (result.userInfo == null) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('登录失败：用户信息为空')));
          setState(() => _isLoading = false);
          return;
        }
        // 保存用户信息到 Provider
        ref.read(authProvider).setUserInfo(result.userInfo!);

        final userInfo = result.userInfo!;

        if (userInfo.approved == true && userInfo.token != null) {
          await ref.read(sessionProvider.notifier).save(
            Session(
              token: userInfo.token,
              unionid: userInfo.unionid,
              merchantId: Env.merchantId,
              role: userInfo.role,
              scopes: userInfo.scopes,
            ),
          );

          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: const Text('登录成功'),
              duration: const Duration(seconds: 1),
              behavior: SnackBarBehavior.floating,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              margin: const EdgeInsets.all(16),
            ),
          );
          // 同步协议状态到服务器
          AgreementManager.syncToServer(ref);
          
          // 刷新本地协议状态
          ref.read(agreementStatusProvider.notifier).refresh();
          
          Future.delayed(const Duration(seconds: 1), () {
            if (!mounted) return;
            GoRouter.of(context).pushReplacement('/tabs');
          });
        } else {
          if (userInfo.hasRecord == false) {
            GoRouter.of(context).pushReplacement('/merchant/profile-fill');
          } else {
            GoRouter.of(context).pushReplacement('/merchant/pending');
          }
        }
      } else {
        if (!mounted) return;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('登录失败：${result.errorMessage ?? '未知错误'}'),
            duration: const Duration(seconds: 2),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
            margin: const EdgeInsets.all(16),
          ),
        );
        setState(() => _isLoading = false);
      }
    }, onError: (error) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('登录流错误：$error'),
          duration: const Duration(seconds: 2),
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          margin: const EdgeInsets.all(16),
        ),
      );
      setState(() => _isLoading = false);
    });
  }

  Future<void> _loginWithWeChat() async {
    if (_isLoading) return;
    setState(() => _isLoading = true);
    try {
      bool success = await WeChatManager.login();
      if (!success) {
        throw Exception('无法发起微信授权请求，请检查配置或网络');
      }
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('登录失败：${e.toString()}'),
          duration: const Duration(seconds: 2),
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          margin: const EdgeInsets.all(16),
        ),
      );
      setState(() => _isLoading = false);
    }
  }

  void _showConfigDialog(BuildContext context) async {
    final config = await showDialog<Map<String, dynamic>>(
      context: context,
      builder: (context) => const ConfigDialog(),
    );
    if (config != null && mounted) {
      await AppConfig.saveConfig(
        config['baseUrl'] as String,
        config['port'] as int,
        config['apiPrefix'] as String,
      );
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('配置已保存'),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            margin: const EdgeInsets.all(16),
          ),
        );
      }
    }
  }

  @override
  void dispose() {
    _authSubscription?.cancel();
    // 不要调用WeChatManager.dispose()，因为这会关闭StreamController
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [_backgroundStart, _backgroundEnd],
          ),
        ),
        child: SafeArea(
          child: Stack(
            children: [
              Center(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.symmetric(horizontal: 24.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const SizedBox(height: 20),
                      // Logo 或标题
                      Icon(Icons.store, size: 80, color: _primaryColor),
                      const SizedBox(height: 16),
                      Text(
                        '欢迎登录',
                        style: TextStyle(
                          fontSize: 28,
                          fontWeight: FontWeight.bold,
                          color: _primaryColor,
                        ),
                      ),
                      const SizedBox(height: 200),
                      // 微信登录按钮
                      ElevatedButton(
                        onPressed:
                            _isWeChatInstalled
                                ? (_isLoading ? null : _loginWithWeChat)
                                : null,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: _primaryColor,
                          padding: const EdgeInsets.symmetric(
                            vertical: 16,
                            horizontal: 32,
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                          elevation: 4,
                          shadowColor: Colors.black26,
                          disabledBackgroundColor: Colors.grey[400],
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            _isLoading
                                ? const SizedBox(
                                  width: 20,
                                  height: 20,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    color: Colors.white,
                                  ),
                                )
                                : const Icon(Icons.wechat, color: Colors.white),
                            const SizedBox(width: 8),
                            Text(
                              _isWeChatInstalled ? '微信一键登录' : '请先安装微信',
                              style: const TextStyle(
                                fontSize: 16,
                                color: Colors.white,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 40),
                      // 底部协议
                      RichText(
                        textAlign: TextAlign.center,
                        text: TextSpan(
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                          children: [
                            const TextSpan(text: '登录即表示您同意'),
                            TextSpan(
                              text: '《用户协议》',
                              style: TextStyle(color: _primaryColor),
                            ),
                            const TextSpan(text: '和'),
                            TextSpan(
                              text: '《隐私政策》',
                              style: TextStyle(color: _primaryColor),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              // 右上角设置按钮
              Positioned(
                top: 16,
                right: 16,
                child: IconButton(
                  icon: const Icon(Icons.settings, color: Colors.grey),
                  onPressed: () => _showConfigDialog(context),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class ConfigDialog extends StatefulWidget {
  const ConfigDialog({super.key});

  @override
  ConfigDialogState createState() => ConfigDialogState();
}

class ConfigDialogState extends State<ConfigDialog> {
  late TextEditingController baseUrlController;
  late TextEditingController portController;
  late TextEditingController apiPrefixController;
  bool _isLoading = true;
  final Color _primaryColor = const Color(0xFF1A73E8);

  @override
  void initState() {
    super.initState();
    _loadDefaultConfig();
  }

  Future<void> _loadDefaultConfig() async {
    try {
      // 从 .env 文件加载默认值，若无则使用硬编码备用值
      final defaultBaseUrl =
          dotenv.env['BASE_URL'] ?? 'https://default.api.example.com';
      final defaultPort = dotenv.env['PORT'] ?? '8080';
      final defaultApiPrefix = dotenv.env['API_PREFIX'] ?? '';

      if (mounted) {
        setState(() {
          baseUrlController = TextEditingController(text: defaultBaseUrl);
          portController = TextEditingController(text: defaultPort);
          apiPrefixController = TextEditingController(text: defaultApiPrefix);
          _isLoading = false;
        });
      }
    } catch (e) {
      // 如果加载 .env 失败，使用硬编码默认值
      if (mounted) {
        setState(() {
          baseUrlController = TextEditingController(
            text: 'https://default.api.example.com',
          );
          portController = TextEditingController(text: '8080');
          apiPrefixController = TextEditingController(text: '');
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        title: const Text(
          '应用配置',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        content: const Center(child: CircularProgressIndicator()),
      );
    }

    return AlertDialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      title: const Text('应用配置', style: TextStyle(fontWeight: FontWeight.bold)),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: baseUrlController,
              decoration: InputDecoration(
                labelText: '请求地址',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: BorderSide(color: _primaryColor),
                ),
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: portController,
              decoration: InputDecoration(
                labelText: '端口号',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: BorderSide(color: _primaryColor),
                ),
              ),
              keyboardType: TextInputType.number,
            ),
            const SizedBox(height: 16),
            TextField(
              controller: apiPrefixController,
              decoration: InputDecoration(
                labelText: 'API 前缀',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: BorderSide(color: _primaryColor),
                ),
              ),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.pop(context, null);
          },
          child: Text('取消', style: TextStyle(color: Colors.grey[600])),
        ),
        TextButton(
          onPressed: () {
            final baseUrl = baseUrlController.text.trim();
            final portText = portController.text.trim();
            final apiPrefix = apiPrefixController.text.trim();

            if (baseUrl.isEmpty || portText.isEmpty) {
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(const SnackBar(content: Text('请填写所有字段')));
              return;
            }

            final port = int.tryParse(portText);
            if (port == null) {
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(const SnackBar(content: Text('端口号必须是数字')));
              return;
            }

            Navigator.pop(context, {
              'baseUrl': baseUrl,
              'port': port,
              'apiPrefix': apiPrefix,
            });
          },
          child: Text(
            '保存',
            style: TextStyle(color: _primaryColor, fontWeight: FontWeight.bold),
          ),
        ),
      ],
    );
  }

  @override
  void dispose() {
    baseUrlController.dispose();
    portController.dispose();
    apiPrefixController.dispose();
    super.dispose();
  }
}
